package richbar.com.richbar.wxapi;

import com.common.util.LogUtil;
import com.luck.picture.lib.tools.Constant;
import com.okhttp.network.HttpUtils;
import com.okhttp.network.MyGson;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import richbar.com.richbar.MainActivity;
import richbar.com.richbar.R;
import richbar.com.richbar.activity.login.BindTelAc;
import richbar.com.richbar.activity.login.LoginAc;
import richbar.com.richbar.activity.me.AccountRelationAc;
import richbar.com.richbar.base.BaseApplication;
import richbar.com.richbar.bean.AccessTokenResult;
import richbar.com.richbar.bean.DeleteRateResult;
import richbar.com.richbar.bean.LoginBean;
import richbar.com.richbar.bean.WxUserInfoResult;
import richbar.com.richbar.help.Constants;
import richbar.com.richbar.util.NetWorkUtil;
import richbar.com.richbar.util.SpUtil;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApplication.iwxapi.handleIntent(getIntent(), this);
    }

/*	@Override
    protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
        BaseApplication.iwxapi.handleIntent(intent, this);

	}*/


    @Override
    public void onReq(BaseReq req) {

    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

        LogUtil.e("LLLLLLLLLLLL", resp.errCode + "---");

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
                    result = R.string.errcode_success;
                } else {
                    if (AccountRelationAc.isBand) {
                        getAccessTokens(((SendAuth.Resp) resp).code);
                    } else if (AccountRelationAc.isBand == false) {
                        getAccessToken(((SendAuth.Resp) resp).code);
                    }
                }

                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = R.string.errcode_cancel;
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = R.string.errcode_deny;
                finish();
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                result = R.string.errcode_unsupported;
                finish();
                break;
            default:
                result = R.string.errcode_unknown;
                finish();
                break;
        }

        Toast.makeText(this, result, Toast.LENGTH_LONG).show();
    }


    private void getAccessToken(String code) {
        LogUtil.e("DWDWPDWWDD", code);
        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append(Constants.APP_ID)
                .append("&secret=")
                .append(Constants.SECRET)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        NetWorkUtil.get(loginUrl.toString(), new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                final AccessTokenResult result = MyGson.getInstance().fromJson(data, AccessTokenResult.class);
                String access = result.getAccess_token();
                final String openId = result.getOpenid();

                //获取个人信息
                String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId;
                NetWorkUtil.get(getUserInfo, new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        final WxUserInfoResult result = MyGson.getInstance().fromJson(data, WxUserInfoResult.class);
                        NetWorkUtil.bindWxStatus(openId, result.getNickname(), result.getHeadimgurl(), new HttpUtils.HttpCallback() {
                            @Override
                            public void onSuccess(String data) {
                                LogUtil.e("DWDAWOFWFOJWF", data);
                                final LoginBean bean = MyGson.getInstance().fromJson(data, LoginBean.class);
                                if (null != bean && bean.getCode().equals("200")) {
                                    if (bean.getData().getStatus().equals("1")) {
                                        //yi绑定
                                        BaseApplication.uid = bean.getData().getUid();
                                        SpUtil.setLoginInfo(WXEntryActivity.this, bean);
                                        LoginAc.sendRefreshBroad(WXEntryActivity.this);
//                                        Intent intent = new Intent(WXEntryActivity.this, MainActivity.class);
//                                        startActivity(intent);
                                        finish();
                                    } else {
                                        Intent intent = new Intent(WXEntryActivity.this, BindTelAc.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable("result", result);
                                        intent.putExtras(bundle);
                                        startActivity(intent);
                                        finish();
                                    }
                                }
                            }
                        });


                    }
                });

            }
        });

    }

    private void getAccessTokens(String code) {
        LogUtil.e("DWDWPDWWDD", code);
        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append(Constants.APP_ID)
                .append("&secret=")
                .append(Constants.SECRET)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        NetWorkUtil.get(loginUrl.toString(), new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                final AccessTokenResult result = MyGson.getInstance().fromJson(data, AccessTokenResult.class);
                String access = result.getAccess_token();
                final String openId = result.getOpenid();

                //获取个人信息
                String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId;
                NetWorkUtil.get(getUserInfo, new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        final WxUserInfoResult result = MyGson.getInstance().fromJson(data, WxUserInfoResult.class);
                        Intent intent = new Intent(WXEntryActivity.this, BindTelAc.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("result", result);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        finish();


                    }
                });

            }
        });
        /*OkHttpUtils.ResultCallback<String> resultCallback = new OkHttpUtils.ResultCallback<String>() {
            @Override
			public void onSuccess(String response) {
				String access = null;
				String openId = null;
				try {
					JSONObject jsonObject = new JSONObject(response);
					access = jsonObject.getString("access_token");
					openId = jsonObject.getString("openid");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				//获取个人信息
				String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId;
				OkHttpUtils.ResultCallback<String> reCallback = new OkHttpUtils.ResultCallback<String>() {
					@Override
					public void onSuccess(String responses) {

						String nickName = null;
						String sex = null;
						String city = null;
						String province = null;
						String country = null;
						String headimgurl = null;
						try {
							JSONObject jsonObject = new JSONObject(responses);

							openid = jsonObject.getString("openid");
							nickName = jsonObject.getString("nickname");
							sex = jsonObject.getString("sex");
							city = jsonObject.getString("city");
							province = jsonObject.getString("province");
							country = jsonObject.getString("country");
							headimgurl = jsonObject.getString("headimgurl");
							unionid = jsonObject.getString("unionid");
							loadNetData(1, openid, nickName, sex, province,
									city, country, headimgurl, unionid);

						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(Exception e) {
						Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
						finish();
					}
				};
				OkHttpUtils.get(getUserInfo, reCallback);
			}

			@Override
			public void onFailure(Exception e) {
				Toast.makeText(WXEntryActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
				finish();
			}
		};
		OkHttpUtils.get(loginUrl.toString(), resultCallback);*/
    }


}